import React, { useEffect, useRef, useState } from "react";
import { Button, Form, Input, Toast } from "antd-mobile";
import $fetch from "../../utils/app/$fetch";
import $getQuery from "../../utils/app/$getQuery";
import { useLogin } from "../../context/LoginContext";
import PrivacyProtocol from "./component/PrivacyProtocol";
import ServiceProtocol from "./component/ServiceProtocol";
import NameComponent from "./component/Name";
import AvatarComponent from "./component/Avatar";
import "./style.scss";

const bg2: any = require("../../asset/imgs/login_bg2.jpg");

const LoginPage = () => {
  const { state, dispatch, fetchLogin, refTimer }: any = useLogin();
  const [form]: any = Form.useForm();
  const refCount: any = useRef<number>();
  const $params: any = $getQuery();
  const { groupId = "" } = { ...$params };
  const currentGroupId = localStorage.getItem("groupId");
  const [bg, setBg] = useState("");
  const [logoTitle, setLogoTitle] = useState("");

  useEffect(() => {
    getBg();
  }, []);

  const getBg = () => {
    const $params: any = $getQuery();
    const { groupId = "" } = { ...$params };
    const groupIdStrorage = localStorage.getItem("groupId");
    const groupIdCurrent = groupId || groupIdStrorage;
    var backImg: any;
    var logoTitle: any;
    switch (groupIdCurrent) {
      case "1":
        backImg = bg2;
        logoTitle = "STARSHIPS";
        break;
    }
    setBg(backImg);
    setLogoTitle(logoTitle);
  };

  // if (
  //   !currentGroupId ||
  //   (currentGroupId && groupId && currentGroupId !== groupId)
  // ) {
  //   localStorage.setItem("groupId", groupId);
  // }

  // 获取验证码的定时器
  const onTimer = () => {
    refTimer.current = setTimeout(() => {
      refCount.current--;
      const opts: any = {
        btnText: `${refCount.current}s后重新获取`,
        activeCode: false,
      };
      if (refCount.current <= 0) {
        opts.btnText = "获取验证码";
        opts.activeCode = true;
        refTimer.current = null;
        clearTimeout(refTimer.current);
        refTimer.current = null;
      } else {
        onTimer();
      }
      dispatch({ ...opts });
    }, 1000);
  };

  const handleMobile = (value: any) => {
    const telephone = value.trim();
    dispatch({
      telephone: telephone,
      activeBtn: state?.authCode && telephone && telephone.length === 11,
      activeCode: !refCount?.current && telephone && telephone.length === 11,
    });
  };

  const handleCode = (value: any) => {
    const authCode = value.trim();

    dispatch({
      authCode: authCode,
      activeBtn: state?.telephone && authCode && authCode.length >= 6,
    });
  };

  const getCode = async () => {
    if (!state?.activeCode) return;
    if (refTimer.current || state.btnText !== "获取验证码") return;
    const telephone = state?.telephone?.trim();

    if (!telephone) {
      Toast.show("请先输入手机号");
      return;
    }
    if (!/^[1][3-9][0-9]{9}$/.test(telephone)) {
      Toast.show("手机号格式有误");
      return;
    }
    // 调用接口获取验证码
    const res: any = await $fetch(
      "customer/getAuthCode",
      { telephone: state?.telephone },
      { noGroupId: "no" }
    );

    refCount.current = 60;
    dispatch({
      btnText: `${refCount.current}s后重新获取`,
      activeCode: false,
    });

    // 拿到验证码，先清除上次定时器，再开始计时60s
    refTimer.current && clearTimeout(refTimer.current);
    onTimer();
  };

  return (
    <div className="container_login">
      <img src={bg} alt="" style={{ width: '100%'}}/>
      <div className="login_wraper">
        <div className="that_header">
          <h2>你好，</h2>
          <h2>欢迎使用{logoTitle} FanClub系统</h2>
          <div className="that_login_code">验证码登录</div>
        </div>
        <Form
          layout="horizontal"
          form={form}
          footer={
            <Button
              disabled={!state?.activeBtn}
              onClick={()=>{
                clearTimeout(refTimer.current);
                fetchLogin()}}
              block
              type="submit"
              color="primary"
              shape="rounded"
            >
              登录
            </Button>
          }
        >
          <Form.Item name="mobile" label={<i className="iconfont">&#xe611;</i>}>
            <Input
              placeholder="请输入手机号"
              type="tel"
              clearable
              maxLength={11}
              value={state?.telephone}
              onChange={handleMobile}
            />
          </Form.Item>
          <Form.Item
            name="authCode"
            label={<i className="iconfont">&#xe623;</i>}
            extra={
              <Button
                disabled={!state?.activeCode}
                className="item_code"
                color="primary"
                fill="none"
                onClick={getCode}
              >
                {state?.btnText}
              </Button>
            }
          >
            <Input
              value={state?.authCode}
              placeholder="请输入验证码"
              type="tel"
              clearable
              maxLength={6}
              onChange={handleCode}
            />
          </Form.Item>
          <div className="that_protocol">
            <em
              onClick={() => dispatch({ isReaded: !state?.isReaded })}
              className={state?.isReaded ? "isChecked" : ""}
            ></em>
            <div>
              已阅读并同意
              <span onClick={() => dispatch({ serviceVisible: true })}>
                《用户协议》
              </span>
              和
              <span onClick={() => dispatch({ privacyVisible: true })}>
                《隐私政策》
              </span>
            </div>
          </div>
        </Form>
        <div className="that_footer">
          <div>联系我们</div>
          <div>地址：上海市浦东新区杨高中路58弄</div>
          <div>邮箱：ifestive365@sina.com</div>
          <div>联系电话：18810629001</div>
        </div>
      </div>

      <ServiceProtocol
        visible={state?.serviceVisible}
        onClose={() => dispatch({ serviceVisible: false })}
      />
      <PrivacyProtocol
        visible={state?.privacyVisible}
        onClose={() => dispatch({ privacyVisible: false })}
      />

      <NameComponent bg={bg}/>
      <AvatarComponent bg={bg}/>
    </div>
  );
};

export default LoginPage;
